//
//  ViewController.m
//  Exam14-2
//
//  Created by 孙晓晔 on 2017/5/4.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"
#import "DownloadOperation.h"
#import "Download.h"

@interface ViewController ()<DownloadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;
@property (weak, nonatomic) IBOutlet UIImageView *imageView3;

@property(nonatomic, strong) NSMutableArray *urls;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self userinfo];
}

// 通过服务端获取用户头像
-(void)userinfo {
    // 设置请求路径
    NSURL *url = [NSURL URLWithString:@"http://vpn.jiapuwang.net/j/one/cn.php?do=User.headimg"];
    
    // 创建请求对象
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    // 创建会话对象
    NSURLSession *urlSession = [NSURLSession sharedSession];
    
    // 发送请求
    NSURLSessionDataTask *urlSessionDataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSError *err;
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
        
        self.urls = [NSMutableArray array];
        
        if (err) {
            NSLog(@"json解析失败：%@",err);
        } else {
            NSInteger count = [arr count];
            
            for (int i = 0; i < count; i++) {
                NSString *img = [[arr objectAtIndex:i] valueForKey:@"headimgurl"];
                [self.urls addObject:img];
            }
            
            Download *download = [[Download alloc]initWithUrl:self.urls];
            download.delegate = self;
            
            [download start:1];
            
            NSLog(@"ok", nil);
        }
    
    }];
    
    // 执行任务
    [urlSessionDataTask resume];
}

// 下载头像和缓存，再显示
-(void)didFinishDownload:(NSDictionary *)dict {
    NSLog(@"全部已下载 = %ld", [dict count]);
    
    for (int i = 0; i < [dict count]; i++) {
        NSString *key = self.urls[i];
        
        if (i == 0) {
            self.imageView1.image = [[UIImage alloc]initWithData:dict[key]];
        }
        
        if (i == 1) {
            self.imageView2.image = [[UIImage alloc]initWithData:dict[key]];
        }
        
        if (i == 2) {
            self.imageView3.image = [[UIImage alloc]initWithData:dict[key]];
        }
    }
}

@end
